package com.jk.demo.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;

/**
 * @author 郭峪诚
 * @version 1.0.0
 * @ClassName EsConfig.java
 * @Description TODO
 * @createTime 2021年03月27日 09:02:00
 */
@Configuration
public class EsConfig {

    private Logger logger = LoggerFactory.getLogger(EsConfig.class);

    @Value("${elasticsearch.ip}")
    private String ip;

    @Value("${elasticsearch.firstPort}")
    private String firstPort;

    @Value("${elasticsearch.secondPort}")
    private String secondPort;

    @Value("${elasticsearch.thirdPort}")
    private String thirdPort;

    @Value("${elasticsearch.clusterName}")
    private String clusterName;

    @Bean
    public TransportClient getTransportClient(){
        logger.info("es初始化……");
        logger.info("连接点1的ip是{}，端口是{}，集群名字是{}",ip,firstPort,clusterName);
        logger.info("连接点2的ip是{}，端口是{}，集群名字是{}",ip,secondPort,clusterName);
        logger.info("连接点2的ip是{}，端口是{}，集群名字是{}",ip,thirdPort,clusterName);
        TransportClient transportClient = null;
        try {
            Settings settings = Settings.builder()
                    .put("cluster.name",clusterName)
                    .put("client.transport.sniff",true)
                    .build();
            transportClient = new PreBuiltTransportClient(settings);
            TransportAddress firstAddress = new TransportAddress(InetAddress.getByName(ip),Integer.parseInt(firstPort));
            TransportAddress secondAddress = new TransportAddress(InetAddress.getByName(ip),Integer.parseInt(secondPort));
            TransportAddress thirdAddress = new TransportAddress(InetAddress.getByName(ip),Integer.parseInt(thirdPort));
            transportClient.addTransportAddress(firstAddress);
            transportClient.addTransportAddress(secondAddress);
            transportClient.addTransportAddress(thirdAddress);
            logger.info("初始化完成……");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("es初始化失败……");
        }
        return transportClient;
    }

}
